import * as services from 'services/food';

export default {

  namespace: 'food',
  //健康可餐对应的接口
  state: {
    data: [],
    detail: {},
  },

  reducers: {
    save(state, action) {
      let { data } = state;
      const { payload: { categories, list, ...rest } } = action;
      if (typeof categories !== 'undefined' && !data.length) {
        data = categories.map((cate) => ({
          label: cate.name,
          value: cate.id,
          children: [],
        }));
      }

      if (typeof list !== 'undefined') {
        const foods = list.map((food) => ({
          label: food.name,
          value: food.id,
          data: food,
        }));

        for (let i = 0, l = list.length; i < l; i++) {
          const food = list[i];
          for (let j = 0, l2 = data.length; j < l2; j++) {
            const cate = data[j];
            if (food.categoryId === cate.value) {
              cate.children = foods;
            }
          }
        }
      }

      const ret = { ...state, data };
      Object.keys(rest).forEach(key => {
        if (typeof rest[key] !== 'undefined') {
          ret[key] = rest[key];
        }
      });
      return ret;
    },

    clear(state) {
      return { ...state, search: null };
    },
  },

  effects: {
    *fetchFoodCategories({ payload }, { call, put }) {
      const FoodCategories = yield call(services.queryFoodCategoryList);
      let food_ = FoodCategories.data;
      for (let i = 0, l = food_.length; i < l; i++) {
        const Foods = yield call(services.queryFoodsByCategory, food_[i].id);
        let FOODs = Foods.data; 
        yield put({
          type: 'save',
          payload: {
            categories: food_ || [],
            list: FOODs || [],
          },
        });
      }
    },

    *fetchFoodDetail({ payload: foodId }, { call, put }) {
      const Food = yield call(services.queryFoodDetail, foodId);
      yield put({ type: 'save', payload: { detail: Food.data || {} } });
    },

    *search({ payload: v }, { call, put }) {
      const Foods  = yield call(services.searchFood, v);
      yield put({ type: 'save', payload: { search: Foods.data || [] } })
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname, query, ...rest }) => {
        if (/foods$/.test(pathname)) {
          dispatch({ type: 'fetchFoodCategories' });
        }

        if (/foods\/\d+/.test(pathname)) {
          dispatch({ type: 'fetchFoodDetail', payload: rest.state.id });
        }
      });
    },
  },
}
